package org.mj.im.sdk.multicaster.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.json.JSONObject;
import org.mj.im.common.enums.IMListenerType;
import org.mj.im.common.model.IMSendResult;
import org.mj.im.sdk.annotation.IMListener;
import org.mj.im.sdk.listener.MessageListener;
import org.mj.im.sdk.multicaster.MessageListenerMulticaster;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Collections;
import java.util.List;

@Component
public class DefaultMessageListenerMulticaster implements MessageListenerMulticaster {
    private List<MessageListener> messageListenerList = Collections.emptyList();

    @Autowired(required = false)
    public DefaultMessageListenerMulticaster(List<MessageListener> messageListenerList) {
        this.messageListenerList = messageListenerList;
    }

    @Override
    public <T> void multicast(IMListenerType listenerType, IMSendResult<T> result) {
        if (CollectionUtil.isNotEmpty(messageListenerList)){
            messageListenerList.forEach(listener->{
                IMListener imListener = listener.getClass().getAnnotation(IMListener.class);
                if (imListener != null &&
                        (IMListenerType.ALL.equals(imListener.listenerType())
                                || imListener.listenerType().equals(listenerType))){
                    if (result.getData() instanceof JSONObject data){
                        Type superInterface = listener.getClass().getGenericInterfaces()[0];
                        Type type = ((ParameterizedType)superInterface).getActualTypeArguments()[0];
                        result.setData(data.toBean(type));
                    }
                    listener.doProcess(result);
                }
            });
        }
    }
}
